export class VersionNotifierSSE {
    constructor(url, options = {}) {
        this.url = url;
        this.currentVersion = options.currentVersion || '';
        this.onUpdateCallback = null;
        this.evtSource = null;
    }

    connect() {
        if (!window.EventSource) {
            console.warn('当前浏览器不支持 EventSource / SSE');
            return;
        }
        this.evtSource = new EventSource(this.url)

        this.evtSource.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.version && data.version !== this.currentVersion) {
                    console.log(`💡 检测到新版本: ${data.version}`);
                    if (this.onUpdateCallback) {
                        this.onUpdateCallback(data.version);
                    } else {
                        if (confirm(`发现新版本 ${data.version}，是否刷新页面？`)) {
                            location.reload();
                        }
                    }
                }
            } catch (error) {
                console.error('解析SSE消息失败:', error);
            }
        }
        this.evtSource.onerror = (err) => {
            console.error('SSE连接错误:', err);
        };
    }

    onUpdate(callback) {
        this.onUpdateCallback = callback
    }

    close() {
        if (this.evtSource) {
            this.evtSource.close()
        }
    }
}